﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting.Internal;
using System.IO;
using System.Text.Json.Nodes;

namespace MyBlog.Controllers
{
    public class UploadController : Controller
    {
        private IWebHostEnvironment _WebHostEnvironment;
        public UploadController(IWebHostEnvironment webHostEnvironment)
        {
            _WebHostEnvironment = webHostEnvironment;
        }

        [HttpPost]
        public IActionResult TinynceImg()
        {
            JsonResult jsonResult = null;
            var files = Request.Form.Files;
            if (files.Count == 0)
            {
                return new JsonResult(new { status = 1, fileName = "", location = "" });//1:上传失败
            }
            var file = files[0];
            var path = _WebHostEnvironment.WebRootPath;
            var UploadDir = "images/rich";
            var fulldir = Path.Combine(path, UploadDir);
            if (!Directory.Exists(fulldir)) Directory.CreateDirectory(fulldir);
            var filename = file.FileName;
            var fullpath = Path.Combine(path, UploadDir, filename);
            using (var fs = new FileStream(fullpath, FileMode.Create, FileAccess.Write))
            {
                file.CopyTo(fs);
                fs.Close();
            }
            var url = $"/{UploadDir}/{filename}";
            //var fi = new fileinfo() { location = url };
            //var s = fi.ToString();
            return new JsonResult(new { status = 0, fileName = filename, location = url });//0:上传成功;
        }

        public IActionResult Image(IFormFile file)
        {
            string fileName = SavePhoto(file);
            if (!"".Equals(fileName))
                return new JsonResult(new { code = 0, msg = "上传成功", name = fileName });
            return new JsonResult(new { code = 1, msg = "上传失败" });
        }

        private string SavePhoto(IFormFile file)
        {
            // wwwroot\images路径
            string uploadFile = Path.Combine(_WebHostEnvironment.WebRootPath, "images", "Cover");
            //生成图片唯一值
            string uniqueFileName = Guid.NewGuid() + "_" + file.FileName;
            //新文件全路径
            string newFileName = Path.Combine(uploadFile, uniqueFileName);
            if(!Directory.Exists(uploadFile)) Directory.CreateDirectory(uploadFile);
            try
            {
                //将图片复制到新文件中
                using (FileStream stream = new FileStream(newFileName, FileMode.Create))
                {
                    file.CopyTo(stream);
                }
            }
            catch (Exception)
            {
                return "";
            }
            return uniqueFileName;
        }
    }
  
}
